package com.lotso.web.common.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * ClassName: HttpUtil
 * Description: Http工具
 * Date: 2019/2/26 16:29 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class HttpUtil {
    private static final RestTemplate REST_TEMPLATE = SpringContextHolder.getBean("restTemplate");


    public static <T> T doGet(String url, Class<T> responseType) {
        return REST_TEMPLATE.getForObject(url, responseType);
    }

    public static <T> T doGet(String url, Class<T> responseType, Map<String, ?> urlVariables) {
        return REST_TEMPLATE.getForObject(url, responseType, urlVariables);
    }

    public static <T> T doPost(String url, String str, Class<T> responseType) {
        HttpEntity<String> entity = new HttpEntity<>(str, createHeader());
        return REST_TEMPLATE.postForObject(url, entity, responseType);
    }

    public static <T> T doPost(String url, String str, Class<T> responseType, Object... uriVariables) {
        HttpEntity<String> entity = new HttpEntity<>(str, createHeader());
        return REST_TEMPLATE.postForObject(url, entity, responseType, uriVariables);
    }

    public static <T> T doPost(String url, String str, Class<T> responseType, Map<String, ?> uriVariables) {
        HttpEntity<String> entity = new HttpEntity<>(str, createHeader());
        return REST_TEMPLATE.postForObject(url, entity, responseType, uriVariables);
    }

    private static HttpHeaders createHeader() {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Accept-Charset", "utf-8");
        requestHeaders.set("Content-type", "text/xml; charset=utf-8");
        requestHeaders.set("Content-type", "text/html; charset=utf-8");
        requestHeaders.set("Content-type", "application/json; charset=utf-8");
        return requestHeaders;
    }
}

